package cn.tedu._04weibo.controller;

import cn.tedu._04weibo.commom.response.JsonResult;
import cn.tedu._04weibo.commom.response.StatusCode;
import cn.tedu._04weibo.mapper.WeiboMapper;
import cn.tedu._04weibo.pojo.dto.WeiboDTO;
import cn.tedu._04weibo.pojo.entity.Weibo;
import cn.tedu._04weibo.pojo.vo.UserVO;
import cn.tedu._04weibo.pojo.vo.WeiboDetailVO;
import cn.tedu._04weibo.pojo.vo.WeiboIndexVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
@Validated
@Slf4j
@Api(tags = "2微博模块")
@RestController
@RequestMapping("v1/weibo/")
public class WeiboController {
    @Autowired(required = false)
    private WeiboMapper weiboMapper;
    /**
     * 发布微博功能
     */
    @ApiOperation("发布微博")
    @PostMapping("insert")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO,@ApiIgnore HttpSession session){
         /*
            1.校验用户登录状态[session]
            2.未登录状态：return 2;
            3.登录状态：在微博表中插入1条数据[接口,实体类]
         */
        UserVO userVO =(UserVO) session.getAttribute("user");
        if (userVO==null){//未登录
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        //实例化,复制属性,调用接口方法
        Weibo weibo=new Weibo();
        BeanUtils.copyProperties(weiboDTO,weibo);
        weibo.setCreated(new Date());
        weibo.setUserId(userVO.getId());
        weiboMapper.insertWeibo(weibo);
        return JsonResult.ok();
    }

    /**
     * 微博首页展示
     * @return
     */
    @ApiOperation("微博首页")
    @GetMapping("selectIndex")
    public JsonResult selectIndex(){
        List<WeiboIndexVO> list = weiboMapper.selectByindex();
        return JsonResult.ok(list);
    }
    /**
     * 微博详情功能
     */
    @ApiImplicitParam(name = "id" ,value = "微博编号",required = true,dataType = "int")
    @ApiOperation("微博详情")
    @GetMapping("selectById")
    public JsonResult selectById(@Range(max = 500,min = 200,message = "ID值必须在200-500之间") @RequestParam int id){
        if(id<=0){
            throw new IllegalArgumentException("ID值无效");
        }
        WeiboDetailVO weiboDetailVO=weiboMapper.selectById(id);
        return JsonResult.ok(weiboDetailVO);
    }

}
